package jetbrains.buildServer.cuta.logic.sheet;

import java.util.Comparator;



/**
 * RowComparator is designed for sorting rows by their cell values.
 *
 * @author Leonid Bushuev from JetBrains
 */
public class RowComparator implements Comparator<Row>
{
    int mySortByColumnNr1 = 0;    // zero-based column number
    int mySortByColumnNr2 = 0;    // zero-based column number
    int mySortDirection = +1;    // +1 or -1


    public RowComparator(int sortByColumnNr1, int sortByColumnNr2, int sortDirection)
    {
        mySortByColumnNr1 = sortByColumnNr1;
        mySortByColumnNr2 = sortByColumnNr2;
        mySortDirection = sortDirection;
    }


    public int compare(Row row1, Row row2)
    {
        if (row1 == row2)
            return 0;
        if (row1 == null)
            return +1;
        if (row2 == null)
            return -1;


        int result = compareByColumn(row1, row2, mySortByColumnNr1);
        if (result == 0 && mySortByColumnNr2 >= 0)
            result = compareByColumn(row1, row2, mySortByColumnNr2);

        return result;
    }


    public int compareByColumn(Row row1, Row row2, int index)
    {
        String value1 = row1.cells.get(index).getText();
        String value2 = row2.cells.get(index).getText();

        int n1 = value1.length(),
            n2 = value2.length();

        if (n1 == 0 && n2 == 0)
            return 0;
        if (n1 == 0)
            return +1; // let's push empty cells down
        if (n2 == 0)
            return -1; // let's push empty cells down

        int result = value1.compareToIgnoreCase(value2);
        if (result == 0)
            result = value1.compareTo(value2);

        return result * mySortDirection;
    }
}
